package com.example.financialsystem.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectChangeListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.example.financialsystem.R;
import com.example.financialsystem.datas.AccountBean;
import com.example.financialsystem.datas.OClassificationBean;
import com.rengwuxian.materialedittext.MaterialEditText;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import models.Book;
import models.Record;
import models.UserVO;
import okhttp3.Request;
import okhttp3.RequestBody;
import others.ServerResponse;
import utils.GsonUtil;
import utils.OkHttpCallback;
import utils.OkhttpUtil;

import static others.Const.IP;
import static others.Const.JSON;
import static others.Const.PORT;
import static others.Const.SUCCESS;
import static others.Const.currentBook;
import static others.Const.currentUserVo;
import static others.Tools.ToastShow;
import static utils.GsonUtil.Json2Class;

public class IncomeRecordFragment extends Fragment implements View.OnClickListener {

    private MaterialEditText editNumber;
    private TextView textClass1;
    private TextView textClass2;
    private LinearLayout classLinear;
    private String firstAccount = "现金";
    private TextView textAccount;
    private EditText editRemark;
    private Button buttonSubmit;

    //收入分类滚轮
    private OptionsPickerView IClassificationOptions;
    private ArrayList<OClassificationBean> IClassFirstItems = new ArrayList<>();
    private ArrayList<ArrayList<String>> IClassSecondItems = new ArrayList<>();
    //账户滚轮
    private OptionsPickerView accountOptions;
    private ArrayList<AccountBean> accountFirstItems = new ArrayList<>();
    private ArrayList<ArrayList<String>> accountSecondItems = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_add_incom, container, false);
        return view;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        LoadIClassOptionData();
        InitIClassOptionPicker();
        LoadAccountOptionData();
        InitAccountOptionPicker();

        editNumber = (MaterialEditText)getActivity().findViewById(R.id.income_number);
        textClass1 = (TextView)getActivity().findViewById(R.id.income_class_1);
        textClass2 = (TextView)getActivity().findViewById(R.id.income_class_2);
        classLinear = (LinearLayout)getActivity().findViewById(R.id.income_class_linear);
        textAccount = (TextView)getActivity().findViewById(R.id.income_account);
        editRemark = (EditText) getActivity().findViewById(R.id.income_remark);
        buttonSubmit = (Button)getActivity().findViewById(R.id.income_submit);
        classLinear.setOnClickListener(this);
        textAccount.setOnClickListener(this);
        buttonSubmit.setOnClickListener(this);

    }

    private void LoadIClassOptionData() {
        IClassFirstItems.add(new OClassificationBean(0, "职业收入", "描述部分"));
        IClassFirstItems.add(new OClassificationBean(0, "其他收入", "描述部分"));

        ArrayList<String> options2Items_00 = new ArrayList<>();
        options2Items_00.add("工资收入");
        options2Items_00.add("利息收入");
        options2Items_00.add("奖金收入");
        options2Items_00.add("兼职收入");
        options2Items_00.add("投资收入");
        ArrayList<String> options2Items_01 = new ArrayList<>();
        options2Items_01.add("礼金收入");
        options2Items_01.add("中奖收入");
        options2Items_01.add("意外来钱");
        options2Items_01.add("经营所得");

        IClassSecondItems.add(options2Items_00);
        IClassSecondItems.add(options2Items_01);
    }

    private void InitIClassOptionPicker() {
        IClassificationOptions = new OptionsPickerBuilder(getContext(),
                new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        //返回的分别是三个级别的选中位置
                        textClass1.setText(IClassFirstItems.get(options1).getPickerViewText());
                        textClass2.setText(IClassSecondItems.get(options1).get(options2));
                    }
                })
                .setTitleText("分类")
                .setCancelText("添加自定义分类")
                .setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0, 1)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(Color.WHITE)
                .setTitleColor(Color.BLACK)
                .setCancelColor(Color.BLACK)
                .setSubmitColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK)
                .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setOutSideColor(0x00000000) //设置外部遮罩颜色
                .setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
                    @Override
                    public void onOptionsSelectChanged(int options1, int options2, int options3) {
                        textClass1.setText(IClassFirstItems.get(options1).getPickerViewText());
                        textClass2.setText(IClassSecondItems.get(options1).get(options2));
                    }
                })
                .build();
        IClassificationOptions.setPicker(IClassFirstItems, IClassSecondItems);//二级选择器
    }

    private void LoadAccountOptionData() {
        //选项一
        accountFirstItems.add(new AccountBean(0, "现金", null));
        accountFirstItems.add(new AccountBean(1, "信用卡", null));
        accountFirstItems.add(new AccountBean(2, "金融账户", null));
        accountFirstItems.add(new AccountBean(3, "虚拟账户", null));
        accountFirstItems.add(new AccountBean(4, "投资账户", null));

        //选项二
        ArrayList<String> options2Items_00 = new ArrayList<>();
        options2Items_00.add("现金(CNY)");
        ArrayList<String> options2Items_01 = new ArrayList<>();
        options2Items_01.add("信用卡(CNY)");
        ArrayList<String> options2Items_02 = new ArrayList<>();
        options2Items_02.add("中国银行(CNY)");
        options2Items_02.add("中国建设银行(CNY)");
        options2Items_02.add("中国农业银行(CNY)");
        options2Items_02.add("中国工商银行(CNY)");
        options2Items_02.add("中国交通银行(CNY)");
        ArrayList<String> options2Items_03 = new ArrayList<>();
        options2Items_03.add("支付宝(CNY)");
        options2Items_03.add("微信钱包(CNY)");
        options2Items_03.add("饭卡(CNY)");
        ArrayList<String> options2Items_04 = new ArrayList<>();
        options2Items_04.add("基金账户(CNY)");
        options2Items_04.add("余额宝(CNY)");
        options2Items_04.add("股票账户(CNY)");

        accountSecondItems.add(options2Items_00);
        accountSecondItems.add(options2Items_01);
        accountSecondItems.add(options2Items_02);
        accountSecondItems.add(options2Items_03);
        accountSecondItems.add(options2Items_04);
        /*数据添加完毕*/
    }

    private void InitAccountOptionPicker() {
        accountOptions = new OptionsPickerBuilder(getContext(),
                new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        //返回的分别是三个级别的选中位置
                        firstAccount = accountFirstItems.get(options1).getPickerViewText();
                        textAccount.setText(accountSecondItems.get(options1).get(options2));
                    }
                })
                .setTitleText("账户")
                .setCancelText("添加自定义分类")
                .setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0, 1)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(Color.WHITE)
                .setTitleColor(Color.BLACK)
                .setCancelColor(Color.BLACK)
                .setSubmitColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK)
                .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                //.setLabels("省", "市", "区")
                .setOutSideColor(0x00000000) //设置外部遮罩颜色
                .setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
                    @Override
                    public void onOptionsSelectChanged(int options1, int options2, int options3) {
                        firstAccount = accountFirstItems.get(options1).getPickerViewText();
                        textAccount.setText(accountSecondItems.get(options1).get(options2));
                    }
                })
                .build();
        accountOptions.setPicker(accountFirstItems, accountSecondItems);//二级选择器
        /*pvOptions.setPicker(options1Items, options2Items,options3Items);//三级选择器*/
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.income_account:
                if (accountOptions!=null) accountOptions.show();
                break;
            case R.id.income_class_linear:
                if (IClassificationOptions!=null) IClassificationOptions.show();
                break;
            case R.id.income_submit:
                String url = "http://" + IP + ":" + PORT + "/portal/record/addRecord.do";
                Record newRecord = ConstructRecord();
                if (newRecord != null) {
                    String jsonData = GsonUtil.class2Json(newRecord);
                    RequestBody requestBody = RequestBody.create(JSON, jsonData);
                    Request request = new Request.Builder()
                            .url(url)
                            .post(requestBody)
                            .build();
                    SendRequest(request);
                }
                break;
        }
    }

    public Record ConstructRecord(){
        String bookId = currentBook.getId();
        String userId = currentUserVo.getId();
        int type = 1;
        int isFamily = currentBook.getType();
        double money = Double.parseDouble(editNumber.getText().toString());
        if (money <= 0){
            ToastShow("请输入正确的金额");
            return null;
        }
        String firstClass = textClass1.getText().toString();
        String secondClass = textClass2.getText().toString();
        String accountClass = firstAccount;
        String secondAccount = textAccount.getText().toString();
        String remark = editRemark.getText().toString();
        Record newRecord = new Record(null,bookId,userId,type,isFamily,money,
                firstClass,secondClass,
                accountClass,secondAccount,
                remark,null,null,null);
        return newRecord;
    }

    public void SendRequest(Request request){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkhttpUtil.SendRequestWithPost(
                            request,
                            new OkHttpCallback(){
                                @Override
                                public void onFinish(String status, String responseData) {
                                    if (status.equals(SUCCESS)){
                                        ServerResponse serverResponse = Json2Class(responseData);
                                        if (serverResponse.getStatus() == 0){
                                            Looper.prepare();
                                            ToastShow("添加记录成功");
                                            Looper.loop();
                                        } else {
                                            Looper.prepare();
                                            ToastShow("添加记录失败，请稍后再试");
                                            Looper.loop();
                                        }
                                    } else {
                                        Looper.prepare();
                                        ToastShow("连接服务器失败,请稍后再试");
                                        Looper.loop();
                                    }
                                }
                            });
                }catch (Exception e){
                    ToastShow("抱歉了亲,我们可能遇到了些麻烦");
                    e.printStackTrace();
                }
            }
        }).run();
    }

}
